<template>
  <div class="dialog-container">
    <el-dialog
      :title="dialogType==='add'?'添加系统人员':dialogType === 'detail'?'系统人员详情':'修改系统人员'"
      :visible="dialogVisible"
      @open="initData"
      @close="closeDialog"
    >
      <el-form
        ref="form"
        :model="dataForm"
        class="dialog-form"
        :rules="rules"
        label-width="150px"
        size="mini"
        :disabled="dialogType === 'detail'"
      >
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="基础信息" name="1">
            <el-row>
              <el-col :span="12">
                <el-form-item label="用户名：" prop="username">
                  <el-input v-model="dataForm.username" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="真实姓名：" prop="realName">
                  <el-input v-model="dataForm.realName" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="角色：" prop="roleId">
                  <el-select v-model="dataForm.roleId" class="w-100">
                    <el-option
                      v-for="(item, index) in roles"
                      :key="index + 'role'"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系方式：" prop="phone">
                  <el-input v-model="dataForm.phone" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="电子邮箱：" prop="email">
                  <el-input v-model="dataForm.email" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="是否为总部领导：" prop="isLeader">
                  <el-select v-model="dataForm.isLeader" class="w-100">
                    <el-option
                      v-for="(item, index) in adminOptions"
                      :key="index + '_admin'"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属企业：" prop="enterpriseId">
                  <el-select v-model="dataForm.enterpriseId" filterable clearable>
                    <el-option
                      v-for="(item, index) in enterpriseIds"
                      :key="index + '_enterpriseIds'"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="项目部：" prop="projectDepartmentId">
                  <el-select v-model="dataForm.projectDepartmentId" filterable clearable>
                    <el-option
                      v-for="(item, index) in projectDepartmentOptions"
                      :key="index + '_projectDepartment'"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="报警通知方式：" prop="pushType">
                  <el-radio-group v-model="dataForm.pushType">
                    <el-radio
                      v-for="(item, index) in pushTypeOptions"
                      :key="index + '_pushType'"
                      :label="item.code"
                    >{{ item.codeName }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="扩展属性" name="2">
            <el-col :span="12">
              <el-form-item label="姓名：" prop="realName">
                <span>{{ dataForm.realName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别：" prop="gender">
                <el-select v-model="dataForm.gender">
                  <el-option
                    v-for="(item, index) in genderOptions"
                    :key="index + '_gender'"
                    :label="item.codeName"
                    :value="item.code"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="地区：" prop="region">
                <Treeselect
                  v-model="dataForm.region"
                  class="w-100 form-treeselect"
                  placeholder="请选择地区"
                  :multiple="false"
                  :options="areaTree"
                  :load-options="loadAreaTree"
                  :normalizer="normalizer"
                  :disabled="dialogType == 'detail'"
                  no-children-text="没有更多了"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身份证号：" prop="idCard">
                <el-input v-model="dataForm.idCard" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="文化程度：" prop="educationLevel">
                <el-select v-model="dataForm.educationLevel">
                  <el-option
                    v-for="(item, index) in educationOptions"
                    :key="index + '_education'"
                    :label="item.codeName"
                    :value="item.code"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出生年月：" prop="birthDate">
                <el-date-picker
                  v-model="dataForm.birthDate"
                  type="date"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择日期"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="职务：" prop="title">
                <el-select v-model="dataForm.title">
                  <el-option
                    v-for="(item, index) in titleOptions"
                    :key="index + '_title'"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入职时间：" prop="entryTime">
                <el-date-picker
                  v-model="dataForm.entryTime"
                  type="date"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择日期"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否签订合同" prop="signContract">
                <el-select v-model="dataForm.signContract">
                  <el-option
                    v-for="(item, index) in signContractOptions"
                    :key="index + '_signContract'"
                    :label="item.codeName"
                    :value="item.code"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="签订劳动合同日期：" prop="contractDate">
                <el-date-picker
                  v-model="dataForm.contractDate"
                  type="date"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择日期"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="证书情况：" prop="certificateStatus">
                <el-select v-model="dataForm.certificateStatus">
                  <el-option
                    v-for="(item, index) in certificateOptions"
                    :key="index + '_certificate'"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="运营部短号：" prop="operationShort">
                <el-input v-model="dataForm.operationShort" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="家庭地址：" prop="homeAddress">
                <el-input v-model="dataForm.homeAddress" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注：" prop="remark">
                <el-input v-model="dataForm.remark" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="运维证书图片" prop="">
                <UploadImageList
                  :url="dataForm.certificateImage"
                  @setUrl="setUrl"
                />
              </el-form-item>
            </el-col>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button :loading="saveLoading" class="sure-btn" size="mini" type="primary" @click="handleSave">保存</el-button>
        <el-button size="mini" class="cancel-btn" @click="closeDialog">取消</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { getDict } from '@/utils/dict'
import { getSectionList } from '@/api/info/allInfo'
import UploadImageList from '@/components/UploadImage/uploadList'
import { create, update } from '@/api/system/user'
import { getRoleList } from '@/api/system/roles'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { LOAD_ROOT_OPTIONS } from '@riophae/vue-treeselect'
import { getTree } from '@/api/system/area'
import { getList } from '@/api/info/projectDepartment'
import { phoneReg, mailReg } from '@/utils/formValidate'
import { getEnterpriseByCd } from '@/api/system/common'

export default {
  name: 'AddUserFormDialog',
  components: { UploadImageList, Treeselect },
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    dialogType: {
      type: String,
      default: 'detail'
    },
    obj: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      activeName: '1',
      saveLoading: false,
      dataForm: {
        id: null,
        username: '',
        realName: '',
        phone: '',
        email: '',
        isLeader: false,
        pushType: 'e021_01',
        birthDate: '',
        gender: 'e031_01',
        roleIds: [],
        projectDepartmentId: '',
        enterpriseId: '',
        region: null,
        educationLevel: '',
        idCard: '',
        homeAddress: '',
        title: '',
        entryTime: '',
        signContract: '',
        contractDate: '',
        certificateStatus: '',
        operationShort: '',
        remark: '',
        certificateImage: '',
        roleId: null,
        password: ''
      },
      rules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
        roleId: [{ required: true, message: '请选择角色', trigger: 'change' }],
        // phone: [{ pattern: phoneReg, required: true, message: '请输入正确的电话号码', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入正确的电话号码', trigger: 'blur' }],
        email: [{ pattern: mailReg, required: true, message: '请输入正确的邮箱', trigger: 'blur' }]
        // enterpriseId: [{ required: true, message: '请输选择所属企业', trigger: 'blur' }]
      },
      adminOptions: [
        { value: false, label: '否' },
        { value: true, label: '是' }
      ],
      pushTypeOptions: [],
      educationOptions: [],
      titleOptions: [],
      signContractOptions: [],
      certificateOptions: [],
      projectDepartmentOptions: [],
      enterpriseIds: [],
      roles: [],
      genderOptions: [],
      normalizer(node) {
        let result = {
          id: node.areaid, label: node.areaname, children: node.children || null
        }
        if (!node.children) {
          result = { id: node.areaid, label: node.areaname }
        }
        return result
      },
      areaTree: null
    }
  },
  created() {
    // 消息推送类型
    this.pushTypeOptions = getDict('e021')
    // 文化程度
    this.educationOptions = getDict('e032')
    // 是否签订合同
    this.signContractOptions = getDict('e034')
    // 证书情况
    this.genderOptions = getDict('e031')
    // 角色
    getRoleList().then(res => {
      this.roles = res.data.obj
      // 不显示 管理员角色
      this.roles.forEach((value, index) => {
        if (value.roleType === 'e036_01') {
          this.roles.splice(index, 1)
        }
      })
    })
    // 项目部
    getList().then(res => {
      this.projectDepartmentOptions = res.data.list
    })
    // 所属企业
    getEnterpriseByCd().then(res => {
      this.enterpriseIds = res.data.list
    })
    getSectionList(['e039_03', 'e039_07']).then(value => {
      value.data.list.forEach(item => {
        if (item.infoType === 'e039_07') {
          // 职务
          this.titleOptions.push(item)
        } else {
          // 证书情况
          this.certificateOptions.push(item)
        }
      })
    })
  },
  methods: {
    handleClick() {

    },
    initData() {
      this.activeName = '1'
      this.saveLoading = false
      if (this.obj) {
        const obj = JSON.parse(JSON.stringify(this.obj))
        if (obj.roles && obj.roles.length > 0) {
          obj.roleIds = obj.roles.map(item => item.id)
          obj.roleId = obj.roleIds[0]
        } else {
          obj.roleIds = []
        }
        this.dataForm = obj
      }
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    async loadAreaTree({ action }) {
      if (action === LOAD_ROOT_OPTIONS) {
        getTree().then(result => {
          var res = JSON.parse(JSON.stringify(result.data.list))
          var data = res
          function exec(array) {
            array.forEach(item => {
              if (!item.children || item.children.length === 0) {
                delete item.children
              } else {
                exec(item.children)
              }
            })
          }
          exec(data)
          this.areaTree = data
        })
      }
    },
    handleSave() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.saveLoading = true
          if (this.dataForm.certificateImage !== '' && this.dataForm.certificateImage !== null) {
            this.dataForm.certificateImage = this.dataForm.certificateImage.substring(1)
          }
          this.dataForm.roleIds = [] // 因为现在是一对一的关系，清空一下
          this.dataForm.roleIds.push(this.dataForm.roleId)
          if (this.dataForm.id) {
            update(this.dataForm).then(() => {
              this.$message({
                type: 'success',
                message: '修改成功'
              })
              this.$emit('flushPage')
              this.$emit('closeDialog')
              this.clearData()
              this.saveLoading = false
            }).catch(() => {
              this.saveLoading = false
            })
          } else {
            var password = Math.round(Math.random() * 1000000)
            this.dataForm.password = password
            create(this.dataForm).then(() => {
              this.$emit('flushPage')
              this.$emit('closeDialog')
              this.clearData()
              this.saveLoading = false
              this.$alert('操作成功,初始密码是：' + password, '消息提示', {
                confirmButtonText: '确定',
                callback: action => {

                }
              })
            }).catch(() => {
              this.saveLoading = false
            })
          }
        }
      })
    },
    closeDialog() {
      this.$emit('closeDialog')
      this.clearData()
      this.$refs['form'].clearValidate()
    },
    clearData() {
      this.dataForm = {
        id: null,
        username: '',
        realName: '',
        phone: '',
        email: '',
        isLeader: false,
        pushType: 'e021_01',
        birthDate: '',
        gender: 'e031_01',
        roleIds: [],
        projectDepartmentId: '',
        region: null,
        educationLevel: '',
        idCard: '',
        homeAddress: '',
        title: '',
        entryTime: '',
        signContract: '',
        contractDate: '',
        certificateStatus: '',
        operationShort: '',
        remark: '',
        jobIds: [],
        certificateImage: ''
      }
      this.roleId = null
    },
    setUrl(url) {
      this.dataForm.certificateImage = this.dataForm.certificateImage + ',' + url
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
